import { saveRecordInitAssignContact } from '@/services/api/api-instruct-record';
import ProForm, { DrawerForm, ProFormInstance, ProFormSelect } from '@ant-design/pro-form';
import { Space, Spin, Tag, Typography } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import React, { useState } from 'react';

interface AssignContactProps {
  formRef: ProFormInstance;
  visibleAssign: boolean;
  assignsContacts: UserData.OrganizationOption[];
  onSave: () => void;
  setVisibleReadReauest: () => void;
  setaccountsLenght: () => void;
}

const AssignContact: React.FC<AssignContactProps> = ({
  formRef,
  visibleAssign,
  assignsContacts,
  onSave,
  setVisibleReadReauest,
  setaccountsLenght,
}) => {
  const [loading, setLoading] = useState(false);

  const [dataTreeAddress, setDataTreeAddressState] = useState<DataNode[]>();
  const [dataCheckTreeContact, setDataCheckTreeContactState] = useState<any>();

  /**
   * 加载组织树请求网络
   */
  const loadAddressTreeData = async () => {
    try {
      setLoading(true);

      const response = await saveRecordInitAssignContact();

      if (response.code === 0) {
        setDataTreeAddressState(readyTreeAddressData(response.data));
      }

      setLoading(false);
    } catch (error) {}
  };

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeAddressData(data: Array<UserData.Organization>): any {
    const treeData = new Array();
    console.log(data);

    if (data) {
      data.forEach((val, idx, array) => {
        if (val.isAddress === 1) {
          treeData.push({
            title: (
              <>
                <span>{val.name}</span>
                {val?.marks && val?.marks.length > 0 && (
                  <>
                    <Space wrap>
                      {val?.marks.map((item) => (
                        <Tag bordered={false} color="orange">
                          {item}
                        </Tag>
                      ))}
                    </Space>
                  </>
                )}
              </>
            ),
            key: val.id,
            children: readyTreeAddressData(val.children as Array<UserData.Organization>),
          });
        }

        if (val.isOrganization === 1) {
          treeData.push({
            title: (
              <>
                <span>{val.name}</span>
                {val?.marks && val?.marks.length > 0 && (
                  <>
                    <Space wrap>
                      {val?.marks.map((item) => (
                        <Tag bordered={false} color="orange">
                          {item}
                        </Tag>
                      ))}
                    </Space>
                  </>
                )}
              </>
            ),
            key: val.id,
            // icon: val.isOrganizationType == 1 ? <BankOutlined />:<HomeOutlined />,
            children: readyTreeAddressData(val.children as Array<UserData.Organization>),
          });
        }

        if (val.isContact === 1) {
          treeData.push({
            title: (
              <>
                <Space>
                  {val.name}
                  {val?.accountPhone != undefined && (
                    <>
                      -
                      <Typography.Paragraph
                        copyable
                        style={{
                          marginBottom: 0,
                        }}
                      >
                        {val.accountPhone}
                      </Typography.Paragraph>
                    </>
                  )}
                </Space>
                {val?.marks && val?.marks.length > 0 && (
                  <>
                    <Space wrap>
                      {val?.marks.map((item) => (
                        <Tag bordered={false} color="orange">
                          {item}
                        </Tag>
                      ))}
                    </Space>
                  </>
                )}
              </>
            ),
            key: val.id,
            // key: val.id.substring(0, val.id.lastIndexOf('-')),
          });
        }
      });
    }
    return treeData;
  }

  return (
    <ProForm.Group
      style={{
        display: visibleAssign ? 'block' : 'none',
      }}
    >
      <ProFormSelect
        name="assignContacts"
        label="已选"
        width="900px"
        style={{
          width: '850px',
        }}
        showSearch
        hidden={!visibleAssign}
        fieldProps={{
          mode: 'multiple',
          allowClear: true,
          showSearch: true,
          open: false,
          optionFilterProp: 'children',
          filterOption: (input: any, option: any) => {
            if (option.label) {
              return option.label.includes(input);
            }
          },
          listHeight: 500,
          style: {
            marginLeft: '28px',
          },
        }}
        rules={[{ required: visibleAssign, message: '请选择至少一个联络人' }]}
        options={assignsContacts}
        onChange={(value) => {
          console.log(value);
          if (value.length === 0) {
            onSave(false);
          }
          setaccountsLenght(value.length);
          // formRef?.current?.setFieldsValue({
          //   completeType: '1',
          // });
          setVisibleReadReauest(false);
        }}
        addonAfter={
          <DrawerForm
            width="500px"
            title="发布范围：联络人（多选）"
            trigger={
              <a key="activeSaveContact" onClick={() => {}}>
                点击添加
              </a>
            }
            autoFocusFirstInput
            drawerProps={{
              destroyOnClose: true,
            }}
            onOpenChange={(visible: boolean) => {
              if (visible) {
                loadAddressTreeData();
                console.log(formRef.current?.getFieldValue('assignContacts'));

                setDataCheckTreeContactState(formRef.current?.getFieldValue('assignContacts'));
              }
              formRef?.current?.setFieldsValue({
                countReceipt: formRef?.current?.getFieldValue('assignContacts')?.length,
              });
            }}
            submitter={false}
            onFinish={async (values) => {}}
          >
            <Spin spinning={loading}>
              {dataTreeAddress && dataTreeAddress.length ? (
                <Tree
                  treeData={dataTreeAddress}
                  checkedKeys={dataCheckTreeContact}
                  checkable
                  selectable={false}
                  onCheck={(checkedKeys, e) => {
                    console.log('========111==========', e.checkedNodesPositions);
                    const checkKeys = new Array();
                    const checkKeys1 = new Array();

                    e.checkedNodesPositions?.map((item) => {
                      if (item.node.children == undefined) {
                        checkKeys.push(item.node.key);
                      }
                    });

                    setDataCheckTreeContactState(checkedKeys);
                    console.log(checkKeys);

                    checkKeys.map((item) => {
                      checkKeys1.push(item.substring(item.lastIndexOf('-') + 1, item.length));
                    });
                    console.log(checkKeys1);

                    if (checkKeys.length > 0) {
                      onSave(true);
                    } else {
                      onSave(false);
                    }
                    console.log(checkKeys);

                    setaccountsLenght(checkKeys.length);
                    formRef.current?.setFieldsValue({
                      assignContacts: checkKeys,
                    });
                  }}
                />
              ) : (
                '暂无数据'
              )}
            </Spin>
          </DrawerForm>
        }
      />
    </ProForm.Group>
  );
};

export default AssignContact;
